
import { Component, OnInit } from '@angular/core';
import { HttpService } from '../http.service';
import { UserService } from '../user.service';
import { PayService } from '../pay.service';
import { Router } from '@angular/router';
import * as ons from 'onsenui';
import {utcToDate} from '../../assets/js/utils'


declare var wx: any;

@Component({
  selector: 'app-apply',
  templateUrl: './apply.component.html',
  styleUrls: ['./apply.component.less']
})
export class ApplyComponent implements OnInit {
  utcToDate=utcToDate;

  constructor(
    private router:Router,
    private http: HttpService,
    private pay: PayService,
    private user: UserService,
  ) {
    this.pay.getJsSDK();
    this.user.getAgentInfo();
  }

  get isAgent() {
    return this.user.isAgent;
  }

  get agentInfo() {
    return this.user.agentInfo.data;
  }

  async apply() {
    const {data, success, msg} = await this.http.post({
      name:'car.pay.agent'
    });
    try {
      await this.pay.pay({
        timestamp: data.pay_need.timestamp_pay,
        nonceStr: data.pay_need.nonceStr_pay,
        package_wx: `prepay_id=${data.wx_return.prepay_id}`,
        signType: 'MD5',
        paySign: data.pay_need.sign_pay
      });
      ons.notification.toast('恭喜!您已成为代理', {timeout: 2000});
      this.user.getUserInfo('compulsive');
      this.user.getAgentInfo('compulsive');
    } catch(err) {
      alert(JSON.stringify(err));
      ons.notification.toast('支付失败或已取消!', {timeout: 2000});
    }
  }

  ngOnInit() {
  }


}
